var moment = require('moment');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var validator = require('validator');

User = new Schema({
  group: {
    type: String,
    default: "normal" // normal, admin
  },

  name: String,
  nickname: String,

  pwd: String,
  pwdFailureTimes: {
    type: Number,
    default: 0,
  },
  lastPwdTryTime: {
    type: Date,
    default: moment().utc().format()
  },
  
  avatar: {
	  type: String,
	  default: ''
  },
  coverplan: {
	  type: String,
	  default: ''
  },
  email: {
	  type: String,
	  default: ''
  },
  local: {
	  type: String,
	  default: ''
  },
  otherblog: {
	  type: String,
	  default: ''
  },
  description: {
	  type: String,
	  default: ''
  },
  verified: {
	  type: Boolean,
	  default: false
  },
  
  sess: {
    type: String,
    default: ''
  },

  created: {
    type: Date,
    default: moment().utc().format()
  },

  lastmod: {
    type: Date,
    default: moment().utc().format()
  },

  // 最后一次登录时间
  lastActivity: {
    type: Date,
    default: moment().utc().format()
  }
});

User.pre("save", function (next) {
  // this.mail = validator.normalizeEmail(validator.trim(this.mail));
  // if (!validator.isEmail(this.mail)) {
  //   return next(new Error("[400]邮箱格式不合法"));
  // }
  // if (!validator.isLength(this.mail, 5, 50)) {
  //   return next(new Error("[400]邮箱长度不合法"));
  // }
  // if (!validator.isLength(this.pwd, 6, 200)) {
  //   return next(new Error("[400]密码长度不合法"));
  // }
  // if (!validator.isLength(this.name, 5, 20)) {
  //   return next(new Error("[400]用户名长度不合法"));
  // }

  this.lastmod = moment().utc().format();

  // if (this.isModified('pwd')) {
  //   this.pwd = this.hashPwd(validator.trim(this.pwd));
  //   this.sess = void 0;
  // }
  return next();
});

User.methods.hashPwd = function (pwd) {
  return bcrypt.hashSync(pwd, bcrypt.genSaltSync(8), null);
};
User.methods.isPwd = function (pwd) {
  return bcrypt.compareSync(pwd, this.pwd);
};

exports.User = mongoose.model("User", User);

exports.User.hashPwd = function (pwd) {
  return bcrypt.hashSync(pwd, bcrypt.genSaltSync(8), null);
};
exports.User.isPwd = function (pwd) {
  return bcrypt.compareSync(pwd, this.pwd);
};
